package cn.edu.tju.elm.model.entity;

import cn.edu.tju.core.model.BaseEntity;
import cn.edu.tju.elm.common.constants.RuleType;
import jakarta.persistence.*;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.Where;

import java.math.BigDecimal;

@Entity
@Table(name = "reward_rule",
        uniqueConstraints = @UniqueConstraint(columnNames = {"rule_key"}))
@Data
@SuperBuilder
@AllArgsConstructor
@NoArgsConstructor
@Where(clause = "is_deleted=false")
@DynamicUpdate
public class RewardRule extends BaseEntity {

    @Enumerated(EnumType.STRING)
    @Column(nullable = false, length = 20)
    private RuleType ruleType;

    @Column(precision = 15, scale = 2)
    private BigDecimal conditionAmount;

    @Column(precision = 15, scale = 2)
    private BigDecimal rewardAmount;

    @Column(precision = 5, scale = 4)
    private BigDecimal rewardRate;

    @Column(nullable = false, columnDefinition = "TINYINT(1) DEFAULT 1")
    private Boolean isActive;

    @Column(name = "rule_key", unique = true, length = 100)
    private String ruleKey; // 唯一标识符

    /**
     * 计算奖励金额
     */
    public BigDecimal calculateReward(BigDecimal amount) {
        if (!isActive) {
            return BigDecimal.ZERO;
        }

        if (conditionAmount != null && amount.compareTo(conditionAmount) >= 0) {
            if (rewardAmount != null) {
                return rewardAmount;
            } else if (rewardRate != null) {
                return amount.multiply(rewardRate).setScale(2, java.math.RoundingMode.HALF_UP);
            }
        }
        return BigDecimal.ZERO;
    }

    /**
     * 计算手续费
     */
    public BigDecimal calculateFee(BigDecimal amount) {
        if (!isActive) {
            return BigDecimal.ZERO;
        }

        if (rewardRate != null) {
            return amount.multiply(rewardRate).setScale(2, java.math.RoundingMode.HALF_UP);
        } else if (rewardAmount != null) {
            return rewardAmount;
        }
        return BigDecimal.ZERO;
    }
}